import json

import cv2
from flask import Blueprint, Response, request

from GlobalValues import globalVal
from service import EquipmentFunctionService


class VideoCamera(object):
    # def __init__(self):
    #     # 通过opencv获取实时视频流
    #     self.video = cv2.VideoCapture(0)
    # def __del__(self):
    # self.video.release()

    def get_frame(self):
        # success, image = self.video.read()
        # success, image = globalVal.vid.read()
        # image = globalVal.frame_queue.get()
        # 因为opencv读取的图片并非jpeg格式，因此要用motion JPEG模式需要先将图片转码成jpg格式图片
        ret, jpeg = cv2.imencode('.jpg', globalVal.live_frame)
        return jpeg.tobytes()


equipment = Blueprint('FunctionController', __name__)


def gen(camera):
    while True:
        frame = camera.get_frame()
        # 使用generator函数输出视频流， 每次请求输出的content类型是image/jpeg
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')


# 页面实时视频
@equipment.route('video_feed')  # 这个地址返回视频流响应
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


# 设备开启
@equipment.route('openEquipmentFunction', methods=['GET', 'POST'])
def openEquipmentFunction():
    # req = json.dumps(request.args)
    # checked = request.args.get("checked")
    return EquipmentFunctionService.openEquipmentFunction()


# 设备关闭
@equipment.route('closeEquipmentFunction', methods=['GET', 'POST'])
def closeEquipmentFunction():
    # req = json.dumps(request.args)
    return EquipmentFunctionService.closeEquipmentFunction()


# 下行设备方法
@equipment.route('downEquipmentFunction', methods=['GET', 'POST'])
def downEquipmentFunction():
    req = json.loads(request.data)
    print(req)

    data = {'data': EquipmentFunctionService.downEquipmentFunction(req)}
    result = json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False)
    return result
